import type { Router } from 'vue-router'
import type { lockState } from '@/types/stores/tabs'
import { useTabsStore } from '@/stores/modules/tabs'
import { useAppsStore } from '@/stores/modules/app'
import { storeToRefs } from 'pinia'
import { authLogin } from '@/router/index'
export const getFirstPath = (info) => {
  let path = info.path
  if (info?.children && info.children.length > 0) {
    const childerPath = getFirstPath(info.children[0])
    if (childerPath.startsWith('/')) {
      path = childerPath
    } else {
      path += childerPath
    }
  }
  return path
}
export function setupRouterGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    if (to.meta.isNoAuth) {
      return next()
    }
    const tabStore = useTabsStore()
    const userStore = useAppsStore()
    const { addVisitedRoute, unlock, getLeaverOne } = tabStore
    const { getLoginStatus: loginStatus } = storeToRefs(userStore)
    const { getLocaks: locks, getCurrenName: currenName } = storeToRefs(tabStore)
    //  未登录自动登录
    if (!loginStatus.value && to.name !== 'Login') {
      const firthPath = await authLogin('')
      if (!to.meta.noLogin) {
        if (!firthPath) next('/login')
        if (to.path === '/') {
          return next(firthPath)
        }
        return next({
          path: to.path,
          query: to.query,
        })
      }
    }
    //  已登录状态前往登录页重定向到首页
    if (to.name === 'Login' && loginStatus.value) {
      const info = router.getRoutes().find((el) => el.path === '/')
      return next(info.children[0].path)
    }
    // 自动添加路由缓存
    await addVisitedRoute(from, to)
    // 解锁缓存组
    if (locks.value.length > 0) {
      const lockIndex = locks.value.findIndex((el: lockState) => {
        return el.childer.some((item) => item.name === to.name)
      })
      if (lockIndex >= 0) {
        const lockInfo: lockState = locks.value[lockIndex]
        const name = lockInfo.childer.at(-1).name
        if (name !== to.name) {
          return next({ name })
        }
        unlock(lockIndex)
      }
    }
    //  详情页被清楚父级路由缓存,找不到选中菜单,跳转到首页
    if (to.meta.isPage && !currenName.value) {
      const info = router.getRoutes().find((el) => el.path === '/')
      return next(getFirstPath(info || router.getRoutes()[0]))
    }
    // 获取一级菜单下标
    getLeaverOne(to)
    //  放行路由
    next()
  })
}
